//
//  TTCountDownButton.m
//  TooToo
//
//  Created by liuning on 15/7/30.
//  Copyright (c) 2015年 MoHao. All rights reserved.
//

#import "TTCountDownButton.h"
#import "AppDelegate.h"
#import "AppManager.h"

@interface TTCountDownButton ()
{
    NSString * defaultTitle;
    NSString * countDownTitle;
    NSTimer * timer;
    NSInteger defaultCount;
    NSInteger curCount;
    
}
@property (nonatomic,assign)BOOL canUse;
@end

@implementation TTCountDownButton

-(void)setUpWithFrame:(CGRect)frame defaultCount:(NSInteger)defaultC defaultTitle:(NSString *)defaultT countDownTitle:(NSString *)countDownT tapped:(TapBlock)block
{
    self.frame = frame;
    [super setTitle:nil style:TTButtonStyleRedCorner tapped:block];
    
    self.layer.cornerRadius = frame.size.height / 2;
    
    defaultTitle = defaultT;
    countDownTitle = countDownT;
    defaultCount = defaultC;
    curCount = defaultC;
    
    self.titleLabel.font = [UIFont systemFontOfSize:12];
    self.canUse = YES;

}

-(void)setDefaultTitle:(NSString *)title
{
    defaultTitle = title;
}

-(void)setCanUse:(BOOL)canUse
{
    _canUse = canUse;
    self.canTap = canUse;
    
    if (canUse) {
        
        curCount = defaultCount;
        [self setTitle:defaultTitle forState:UIControlStateNormal];
        
    }
}

-(void)timerFireMethod:(NSTimer *)sender
{
    curCount--;
    
    [self setTitle:[NSString stringWithFormat:@"%ld%@",(long)curCount,countDownTitle] forState:UIControlStateNormal];
    
    if (curCount<=0) {
        
        [self timerStop];
    }
    
}

-(void)timerBegin
{
    [self timerStop];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
    self.canUse = NO;
    
    AppManager * mng = [AppManager sharedManager];
    mng.needPlayBackgroud = YES;
}

-(void)timerStop
{
    [timer invalidate];
    timer = nil;
    
    self.canUse = YES;
    
    AppManager * mng = [AppManager sharedManager];
    mng.needPlayBackgroud = NO;
}
@end
